﻿/// <reference path="~/Scripts/Library/jquery-1.9.1.min.js" />

/// <reference path="~/Scripts/Application/Physis_jqGridSupport.js" />

var postbackController = "SecurityManagement";

function ConfigurationItem_Validate() {

    var isValid = true;

    var lastResponseMessageLabel = $("#LastResponseMessageLabel");


    // SERIALIZE THE ROLE MEMBERSHIP 

    $("#RoleMembership").val(JSON.stringify(roleMembership));


    if ($("#ConfigurationItem_Name").val() == "") {

        $("#RegisterUserAccountSelected").closest("tr").children().first().addClass("ui-state-error");

        $($("#PropertyTabs>ul>li")[1]).addClass("ui-state-error");

    }


    return isValid;

}

function ConfigurationItem_OnReady() {

    // EFFECTIVE PERMISSIONS 

    $("#PropertyTabs li a")[3].click(); // SELECT ROLES TAB     

    ProgressBar_AjaxUnder_Initialize("EffectivePermissions_EnvironmentSelection_ProgressBar");

    $("#EffectivePermissions_EnvironmentSelection").prepend($("<option value=\"0\">(Enterprise)</option>"));

    $("#EffectivePermissions_EnvironmentSelection").val("0");

    EffectivePermissionsGrid_Initialize([]);


    // ROLES
    
    $("#PropertyTabs li a")[2].click(); // SELECT ROLES TAB 

    ProgressBar_AjaxUnder_Initialize("Roles_RoleSelection_ProgressBar");

    $("#Roles_EnvironmentSelection").prepend($("<option value=\"0\">(Enterprise)</option>"));

    $("#Roles_EnvironmentSelection").val("0");

    Roles_EnvironmentSelection_OnChange();

    UserAccountRoleGrid_Initialize();


    // NEW USER ACCOUNT REGISTRATION 

    if ($("#ConfigurationItem_Id").val() == "0") {

        $("#PropertyTabs li a")[1].click(); //SELECT REGISTER TAB 

        $($("#PropertyTabs li")[0]).hide(); // HIDE GENERAL TAB 

        RegisterUserAccountGrid_Initialize();

    }

    else {

        $("#PropertyTabs li a")[0].click(); //SELECT REGISTER TAB 

        $($("#PropertyTabs li")[1]).hide(); // HIDE REGISTER TAB FOR EXISTING USERS 

        $("#ConfigurationItem_Name").attr("disabled", "disabled");

        $("#ConfigurationItem_Description").attr("disabled", "disabled");

    }


}


// REGISTER 

function RegisterUserAccountGrid_Initialize() {

    var requestUrl = $("#RootUrl").val() + "SecurityManagement/UsersBySecurityProvider";
    
    requestUrl += "?SecurityAuthorityId=" + $("#UserAccount_SecurityAuthorityId").val();

    requestUrl += "&UserAccountName=" + $("#UserAccountName").val();

    $("#RegisterUserAccountGrid").jqGrid({

        width: 0,

        height: 325,

        url: requestUrl,

        datatype: "json",

        rowNum: 50,

        rowList: [5, 10, 25, 50],

        colModel: 
            
        [

            { name: "Name" },

            { name: "DisplayName", label: "Display Name" },

            { name: "DistinguishedName", label: " Distinguished Name" }

        ],

        pager: "#RegisterUserAccountGridPager",

        loadComplete: function (data) { RegisterUserAccountGrid_OnLoadComplete(data); },

        loadError: function (xhr, status, error) { RegisterUserAccountGrid_OnLoadError(xhr, status, error); },

        onSelectRow: function (rowId) { RegisterUserAccountGrid_OnSelectRow(rowId); }

    });

    jqGrid_RemoveCorners("RegisterUserAccountGrid");

    jqGrid_ResizeToFitWidth("RegisterUserAccountGrid");

    // CLEAR PERVIOUS SLECTIONS 

    RegisterUserAccount_ClearSelection();

}

function RegisterUserAccountGrid_OnLoadComplete(data) {

    return;

}

function RegisterUserAccountGrid_OnLoadError(xhr, status, error) {

    alert("Error Loading Data from the Server: " + error);

    return;

}

function RegisterUserAccountGrid_OnSelectRow(rowId) {

    var selectedName = $("#RegisterUserAccountGrid").jqGrid("getCell", rowId, "Name");

    var selectedDisplayName = $("#RegisterUserAccountGrid").jqGrid("getCell", rowId, "DisplayName");

    var selectedDistinguishedName = $("#RegisterUserAccountGrid").jqGrid("getCell", rowId, "DistinguishedName");


    $("#RegisterUserAccountSelected").html(selectedName + " (" + selectedDisplayName + ")");

    $("#ConfigurationItem_Name").val(selectedName);

    $("#ConfigurationItem_Description").val(selectedDisplayName);

    $("#UserAccount_DistinguishedName").val(selectedDistinguishedName);

    $("#UserAccount_DisplayName").val(selectedDisplayName);
    

}

function RegisterUserAccountGrid_Refresh() {

    $("#RegisterUserAccountGrid").jqGrid().GridUnload();

    RegisterUserAccountGrid_Initialize();

}

function RegisterUserAccount_ClearSelection() {

    $("#ConfigurationItem_Name").val("");

    $("#ConfigurationItem_Description").val("");

    $("#UserAccount_DistinguishedName").val("");

    $("#UserAccount_DisplayName").val("");

    $("#RegisterUserAccountSelected").val("none");

}


// ROLES 

function UserAccountRoleGrid_Formatters_EnvironmentName(cellValue, options, rowObject) {

    if (rowObject.EnvironmentName == "") {

        rowObject.EnvironmentName = "(Enterprise)";

        return "(Enterprise)";

    }

    return cellValue;

}

function UserAccountRoleGrid_Formatters_Action(cellValue, options, rowObject) {

    return "<a href=\"javascript:void(0);\" onclick=\"Roles_RoleRemove_OnClick(this);\">(remove)</a>";

}

function UserAccountRoleGrid_Initialize() {

    $("#UserAccountRoleGrid").jqGrid({

        width: 0,

        height: 325,

        datatype: "local",

        data: roleMembership,

        rowNum: 99999,

        colModel:

        [

            { name: "EnvironmentName", label: "Environment", formatter: UserAccountRoleGrid_Formatters_EnvironmentName },

            { name: "RoleId", hidden: true },

            { name: "RoleName", search: true },

            { name: "Action", width: "80px", fixed: true, search: false, align: "center", formatter: UserAccountRoleGrid_Formatters_Action }

        ]

    });
    
    $("#UserAccountRoleGrid").jqGrid("filterToolbar", { searchOnEnter: true } );

    jqGrid_RemoveCorners("UserAccountRoleGrid");

    jqGrid_ResizeToFitWidth("UserAccountRoleGrid");

}

function UserAccountRoleGrid_Refresh() {

    $("#UserAccountRoleGrid").jqGrid().GridUnload();

    UserAccountRoleGrid_Initialize();

}


function RoleMembership_ContainsRole(roleId) {

    for (var currentIndex = 0; currentIndex < roleMembership.length; currentIndex++) {

        if (roleMembership[currentIndex].RoleId == roleId) { return true; }

    }

    return false;

}

function RoleMembership_Remove(roleId) {

    var removeIndex = -1;

    for (var currentIndex = 0; currentIndex < roleMembership.length; currentIndex++) {

        var membership = roleMembership[currentIndex];

        if (membership.RoleId == roleId) {

            removeIndex = currentIndex;

            break;

        }

    }

    if (removeIndex >= 0) {

        roleMembership = roleMembership.removeAt(removeIndex);

    }

}


function Roles_EnvironmentSelection_OnChange() {

    $("#Roles_RoleSelection").empty();

    $("#Roles_RoleSelection").append($("<option value=\"\">Loading ...</option>"));

    ProgressBar_AjaxUnder_On("Roles_RoleSelection");

    $("#Roles_RoleAdd").hide();


    var requestUrl = $("#RootUrl").val() + "SecurityManagement/RolesByEnvironment";

    requestUrl += "?EnvironmentId=" + $("#Roles_EnvironmentSelection").val();

    $.ajax({

        url: requestUrl,

        error: function (jqXHR, textStatus, errorThrown) { 

            $("#Roles_RoleSelection").empty();

            $("#Roles_RoleSelection").append($("<option value=\"\">Error: " + errorThrown + "</option>"));

        },

        success: function (response, textStatus, jqXHR) {

            $("#Roles_RoleSelection").empty();

            for (var currentIndex = 0; currentIndex < response.Objects.length; currentIndex++) {

                if (!RoleMembership_ContainsRole(response.Objects [currentIndex].Id)) {

                    $("#Roles_RoleSelection").append($("<option value=\"" + response.Objects[currentIndex].Id + "\">" + response.Objects[currentIndex].Name + "</option>"));

                }

            }

            if ($("#Roles_RoleSelection option").length > 0) {

                $("#Roles_RoleAdd").show();

            }

        },

        complete: function () {

            ProgressBar_AjaxUnder_Off("Roles_RoleSelection");

        }

    });

}

function Roles_RoleAdd_OnClick() {

    var environmentId = $("#Roles_EnvironmentSelection").val();

    var environmentName = $("#Roles_EnvironmentSelection option[value=" + environmentId + "]")[0].innerHTML

    var roleId = $("#Roles_RoleSelection").val();

    var roleName = $("#Roles_RoleSelection option[value=" + roleId + "]")[0].innerHTML


    if (!RoleMembership_ContainsRole(roleId)) {

        var roleMembershipEntry = JSON.parse(JSON.stringify(roleMembershipBaseObject));

        roleMembershipEntry.EnvironmentName = environmentName;

        roleMembershipEntry.RoleId = roleId;

        roleMembershipEntry.RoleName = roleName;

        roleMembership.push(roleMembershipEntry);

        UserAccountRoleGrid_Refresh();

    }

    // NO NEED TO REFRESH THE DROP DOWN AS THE ROLE ID IS UNIQUE WITHIN AN ENVIRONMENT

    // WE WILL SIMPLY LOOK FOR THE ROLE ID IN THE DROP DOWN, AND IF IT EXISTS, REMOVE IT 

    $("#Roles_RoleSelection option[value=" + roleId + "]").remove();

    if ($("#Roles_RoleSelection option").length == 0) {

        $("#Roles_RoleAdd").hide();

    }

}

function Roles_RoleRemove_OnClick(sender) {

    var tableRow = $(sender).closest("tr");

    if (tableRow.length > 0) {

        dataRowId = tableRow[0].id;

        var environmentName = $("#UserAccountRoleGrid").jqGrid("getCell", dataRowId, "EnvironmentName"); // RESERVED FOR FUTURE USE

        // ENVIRONMENT NAME COULD BE USE TO SELECTIVE ADD BACK TO THE ROLE SELECTION WITHOUT A POSTBACK

        // WE WOULD ALSO NEED THE ENVIRONMENT ID TO PERFORM THIS SUCCESSFULLY, WHICH WOULD REQUIRE SERIALIZING IT 

        var roleId = $("#UserAccountRoleGrid").jqGrid("getCell", dataRowId, "RoleId");
        
        RoleMembership_Remove(roleId);

        $("#UserAccountRoleGrid").jqGrid("delRowData", dataRowId);

        Roles_EnvironmentSelection_OnChange();

    }

}


// EFFECTIVE PERMISSIONS 

function EffectivePermissionsGrid_Initialize(dataSet) {

    var requestUrl = $("#RootUrl").val() + "SecurityManagement/EffectivePermissions";

    requestUrl += "?EnvironmentId=" + $("#EffectivePermissions_EnvironmentSelection").val();

    $("#EffectivePermissionsGrid").jqGrid({

        width: 0,

        height: 325,

        url: requestUrl,

        datatype: "local",

        data: dataSet,

        rowNum: 99999,

        colModel:

        [

           { name:"Name", label: "Name" }

        ],

        //loadComplete: function (data) { RegisterUserAccountGrid_OnLoadComplete(data); },

        //loadError: function (xhr, status, error) { RegisterUserAccountGrid_OnLoadError(xhr, status, error); },

        //onSelectRow: function (rowId) { RegisterUserAccountGrid_OnSelectRow(rowId); }

        zzzz: []

    });

    $("#EffectivePermissionsGrid").jqGrid("filterToolbar", { searchOnEnter: true });

    jqGrid_RemoveCorners("EffectivePermissionsGrid");

    jqGrid_ResizeToFitWidth("EffectivePermissionsGrid");

}

function EffectivePermissions_Calculate_OnClick() {

    ProgressBar_AjaxUnder_On("EffectivePermissions_EnvironmentSelection");


    var requestUrl = $("#RootUrl").val() + "SecurityManagement/PermissionsCalculatedForRolesByEnvironment";

    requestUrl += "?EnvironmentId=" + $("#EffectivePermissions_EnvironmentSelection").val();

    $.ajax({

        url: requestUrl,

        method: "POST",

        data: "Role.Membership=" + JSON.stringify(roleMembership),

        error: function (jqXHR, textStatus, errorThrown) {

            $("#LastResponseMessageLabel").html(errorThrown);

        },

        success: function (response, textStatus, jqXHR) {

            $("#EffectivePermissionsGrid").jqGrid().GridUnload();

            EffectivePermissionsGrid_Initialize(response.Objects);

        },

        complete: function () {

            ProgressBar_AjaxUnder_Off("EffectivePermissions_EnvironmentSelection");

        }

    });

}
